package chapter10_3_semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author Summerday
 */
public class SemaphoreTest {
    // 创建一个Semaphore 实例
    private static final Semaphore semaphore = new Semaphore(0);

    public static void main (String[] args) throws InterruptedException {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);



        // 将A添加到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run () {
                System.out.println(Thread.currentThread() + " over ");
                semaphore.release();
            }
        });


        // 将B添加到线程池
        executorService.submit(new Runnable() {
            @Override
            public void run () {
                System.out.println(Thread.currentThread() + " over ");
                semaphore.release();
            }
        });
        Thread.sleep(2000);

        System.out.println(semaphore);
        System.out.println(semaphore.availablePermits());
        semaphore.drainPermits();
        // 等待子线程执行完毕, 返回
        semaphore.acquire(2);


        System.out.println("all child thread over !");

        // 关闭线程池
        executorService.shutdown();
    }

}
